package com.sphd.education.activitys;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.CityGpsInfo;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.HistoryInfo;
import com.sphd.education.info.LessonInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.info.SchoolImgInfo;
import com.sphd.education.info.SchoolInfo;
import com.sphd.education.info.SchoolTeacherImgInfo;
import com.sphd.education.info.ScoreInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.services.LessonSaveService;
import com.sphd.education.view.materialfavoritebutton.MaterialFavoriteButton;
import com.sphd.education.view.tagview.TagCloudView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 课程详情
 */
public class LessonInfoActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.lesson_img)
    ImageView lessonImg;
    @Bind(R.id.lesson_name_textview)
    TextView lessonNameTextview;
    @Bind(R.id.lesson_jianjie)
    TextView lessonJianjie;
    @Bind(R.id.yuan_price_textview)
    TextView yuanPriceTextview;
    @Bind(R.id.now_price_textview)
    TextView nowPriceTextview;
    @Bind(R.id.goschool_btn)
    Button goschoolBtn;
    @Bind(R.id.addname_btn)
    Button gonameBtn;
    @Bind(R.id.guanggao_textview)
    TextView guanggaoTextview;
    @Bind(R.id.message_lesson_name)
    TextView messageLessonName;

    @Bind(R.id.message_lesson_time)
    TextView messageLessonTime;

    @Bind(R.id.relation_phone_img)
    ImageView relationPhoneImg;
    @Bind(R.id.relation_phone)
    TextView relationPhone;
    @Bind(R.id.relation_address)
    TextView relationAddress;
    @Bind(R.id.details_xiangqing_textview)
    TextView detailsXiangqingTextview;
    @Bind(R.id.getcard_cardname_textview)
    TextView getcardCardnameTextview;
    @Bind(R.id.tag_cloud_view_studentside)
    TagCloudView tagCloudViewStudentside;//学院再说的标签
    @Bind(R.id.start_time)
    TextView startTime;
    @Bind(R.id.end_time)
    TextView endTime;
    boolean favorite = false;
    private Intent intent;
    private Context context;
    private Bundle bundle;
    private List<LessonInfo> lessonInfos;
    private String flag;
    private MaterialFavoriteButton toolbarFavorite;
    private int lesson_id;
    private int collect = 0;
    private MyInfo myInfo;
    private String cityName;
    private CityGpsInfo cityGpsInfo;
    LessonInfo lessonInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson_info);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initView();
    }
    /**
     * 给所有控件赋值
     */
    private void setLessonInfo() {
        lessonNameTextview.setText(lessonInfo.getName());
        lessonJianjie.setText(lessonInfo.getClassSchedule());
        yuanPriceTextview.setText("原价:" + lessonInfo.getTuition());
        yuanPriceTextview.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        nowPriceTextview.setText("现价:" + lessonInfo.getRealTuition());
        messageLessonName.setText("课程:" + lessonInfo.getName());
        messageLessonTime.setText("课时:" + lessonInfo.getPeriod());
        relationAddress.setText("上课地址:" + lessonInfo.getPlace());
        relationPhone.setText("热线电话:" + lessonInfo.getPhone());
        startTime.setText("开始时间:" + lessonInfo.getBeginTime());
        endTime.setText("毕业时间:" + lessonInfo.getEndTime());
        detailsXiangqingTextview.setText(lessonInfo.getDescription());
        getcardCardnameTextview.setText(lessonInfo.getCertificate()
                + "\n" + lessonInfo.getCertificateDesc());
        guanggaoTextview.setText(lessonInfo.getAds());
        ImageLoader.getInstance().displayImage(EducationUrl.HttpTitle + "/" + lessonInfo.getImage(), lessonImg, setLessonImg());
    }

    @Override
    public void initView() {
        intent = getIntent();
        context = LessonInfoActivity.this;
        bundle = intent.getBundleExtra(EducationIntentKey.LESSON);
        lesson_id = bundle.getInt("lessonId");
        cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);
        if (cityGpsInfo.isQiecity()) {
            cityName = cityGpsInfo.getOthercity();
        } else {
            cityName = cityGpsInfo.getLoacalcity();
        }
        lessonInfo = new LessonInfo();
        myNet();
        myInfo = DataSupport.findLast(MyInfo.class);
        flag = bundle.getString(EducationIntentKey.FLAG);
        //需要后台进行存储处理否则学校跳转会崩溃
        lessonInfos = DataSupport.where("lesson_id = ?", "" + lessonInfo.getLesson_id()).find(LessonInfo.class);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//这是自带的箭头的返回的监听
            }
        });
        getStudentSide();
    }


    @Override
    public void findViewById() {

    }

    @Override
    public void myNet() {
        showMyDialog();
        StringRequest myLessonInfo = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.LessonInfoUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        getLessonInfo(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissMyDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", "" + lesson_id);
                MyInfo myInfo = DataSupport.findLast(MyInfo.class);
                if (myInfo.getUserid() != 0 && myInfo != null) {
                    map.put("memberId", "" + myInfo.getUserid());
                }
                Log.e("map", map.toString());
                return map;
            }
        };
        myLessonInfo.setTag(EducationIntentKey.LESSON_INFO);
        EducationApplication.getRequestQueue().add(myLessonInfo);
        EducationApplication.getRequestQueue().start();
    }

    @OnClick(R.id.relation_phone_img)
    public void callTel() {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + lessonInfo.getPhone()));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        startActivity(intent);
    }
    private void getLessonInfo(String json) {
        Log.e("JSON", json + "");
        dismissMyDialog();
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has("id"))
                lessonInfo.setLesson_id(jsonObject.getInt("id"));
            if (jsonObject.has("description"))
                lessonInfo.setDescription(jsonObject.getString("description"));
            if (jsonObject.has("lessonName"))
                lessonInfo.setName(jsonObject.getString("lessonName"));
            if (jsonObject.has("startDate"))
                lessonInfo.setBeginTime(jsonObject.getString("startDate"));
            if (jsonObject.has("realTuition"))
                lessonInfo.setRealTuition(jsonObject.getString("realTuition"));
            if (jsonObject.has("logoPath"))
                lessonInfo.setImage(jsonObject.getString("logoPath"));
            if (jsonObject.has("CUM"))
                lessonInfo.setAds(jsonObject.getString("CUM"));
            if (jsonObject.has("classSchedule"))
                lessonInfo.setClassSchedule(jsonObject.getString("classSchedule"));
            if (jsonObject.has("tuition"))
                lessonInfo.setTuition(jsonObject.getString("tuition"));
            if (jsonObject.has("endDate"))
                lessonInfo.setEndTime(jsonObject.getString("endDate"));
            if (jsonObject.has("place"))
                lessonInfo.setPlace(jsonObject.getString("place"));
            if (jsonObject.has("period"))
                lessonInfo.setPeriod(jsonObject.getString("period"));
            if (jsonObject.has("phone"))
                lessonInfo.setPhone(jsonObject.getString("phone"));
            if (jsonObject.has("certificate"))
                lessonInfo.setCertificate(jsonObject.getString("certificate"));
            if (jsonObject.has("certificateDesc"))
                lessonInfo.setCertificateDesc(jsonObject.getString("certificateDesc"));
            if (jsonObject.has("name"))
                lessonInfo.setBanji(jsonObject.getString("name"));
            //appliedSize 为报名人数的字段名
            if (jsonObject.has("appliedSize")) {
                lessonInfo.setAppliedSize(jsonObject.getInt("appliedSize"));
            }
            if (jsonObject.has("size")) {
                lessonInfo.setAllSize(jsonObject.getInt("size"));
            }
            if (jsonObject.has("headTeacherName")) {
                if (jsonObject.getString("headTeacherName").equals("")) {
                    lessonInfo.setTeacherName("暂无老师");
                } else {
                    lessonInfo.setTeacherName(jsonObject.getString("headTeacherName"));
                }
            }
            if (jsonObject.has("creator")) {
                lessonInfo.setCreatorId(jsonObject.getInt("creator"));
            }
            if (jsonObject.has("flag")) {//收藏的字段1和0
                lessonInfo.setCollectflag(jsonObject.getInt("flag"));
                Log.e("FLAG=",jsonObject.getInt("flag")+"");
                if (lessonInfo.getCollectflag() == 0) {
                    toolbarFavorite.setFavorite(false);
                    favorite=false;
                } else {
                    toolbarFavorite.setFavorite(true);
                    favorite=true;
                }
            }

            if (jsonObject.has("organization")) {
                JSONObject schoolJson = new JSONObject(jsonObject.getString("organization"));
                if (schoolJson.has("name"))
                    lessonInfo.setSchoolName(schoolJson.getString("name"));
                if (schoolJson.has("id"))
                    lessonInfo.setSchoolid(schoolJson.getInt("id"));
                if (schoolJson.has("area")) {
                    JSONObject areaJsonObject = new JSONObject(schoolJson.getString("area"));
                    if (areaJsonObject.has("name")) {
                        lessonInfo.setSchoolArea(cityName + areaJsonObject.getString("name"));
                    }
                }
            }
            setLessonInfo();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*
    * 去学校转转的跳转
    * */
    @OnClick(R.id.goschool_btn)
    public void setOnClickGotoSchool() {
//        initSchoolInfo();
        bundle.putInt(EducationIntentKey.SCHOOL_INFO, lessonInfo.getSchoolid());
        bundle.putString(EducationIntentKey.FLAG, flag);
        intent.putExtra(EducationIntentKey.SCHOOL, bundle);
        intent.setClass(context, SchoolInfoActivity.class);
        startActivity(intent);
    }
/*
* 预约报名
*
* */
    @OnClick(R.id.addname_btn)
    public void setOnClickAddName() {
        bundle.putSerializable(EducationIntentKey.LESSON_INFO, lessonInfo);
        intent.putExtra(EducationIntentKey.LESSON, bundle);
        intent.setClass(context, AddNameActivity.class);
        startActivity(intent);


    }

    private void getStudentSide() {
        List<String> tags = new ArrayList<>();
        //添加的虚拟标签
        for (int i = 0; i < 20; i++) {
            tags.add("很好" + i);
        }

        tagCloudViewStudentside.setTags(tags);
        tagCloudViewStudentside.setOnTagClickListener(new TagCloudView.OnTagClickListener() {
            @Override
            public void onTagClick(int position) {
                if (position == -1) {
                    tagCloudViewStudentside.singleLine(false);
                    Toast.makeText(getApplicationContext(), "点击展开标签",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "点击 position : " + position,
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initSchoolInfo() {
        List<SchoolInfo> schoolInfoList = DataSupport.where("school_id=?",""+lessonInfo.getSchoolid()).find(SchoolInfo.class);
        if(schoolInfoList.size()!=0){
            DataSupport.delete(SchoolInfo.class,schoolInfoList.get(0).getId());
        }

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_shouchang, menu);
        toolbarFavorite = (MaterialFavoriteButton) MenuItemCompat.getActionView(menu
                .findItem(R.id.menu_shouchang));
        toolbarFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myInfo == null || myInfo.getUserid() == 0) {
                    toolbarFavorite.setFavorite(false);
                    favorite = false;
                    EducationUrl.showToast(context, "尚未登录");
                    intent.setClass(context, LoginActivity.class);
                    startActivityForResult(intent, 1);
                } else {
                    collectLesson();//收藏 或者取消
                }
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.menu_shouchang) {
            return true;
        }else if (id==R.id.menu_fenxaing){
            GetandSaveCurrentImage();
        }

        return super.onOptionsItemSelected(item);
    }
    private void collectLesson() {
            final StringRequest stringRequest = new StringRequest(Request.Method.POST,
                    EducationUrl.HttpTitle + EducationUrl.Collect,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            switch (response){
                                case "yes":
                                    EducationUrl.showToast(context, "收藏成功");
                                    toolbarFavorite.setFavorite(true);
                                    favorite=true;
                                    break;
                                case "re":
                                    EducationUrl.showToast(context, "取消收藏");
                                    toolbarFavorite.setFavorite(false);
                                    favorite=false;
                                    break;
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("memberId", myInfo.getUserid() + "");
                    map.put("type", 2 + "");
                    map.put("collectID", lessonInfo.getLesson_id() + "");
                    if (favorite) {
                        map.put("cType", 0+ "");
                    } else {
                        map.put("cType", 1 + "");
                    }
                    return map;
                }
            };
            stringRequest.setTag(EducationIntentKey.COLLECT_LESSON_INFO);
            EducationApplication.getRequestQueue().add(stringRequest);
            EducationApplication.getRequestQueue().start();
    }
    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode==EducationIntentKey.LOGONCODE){
                Log.e("onActivityResult","onActivityResult");
                myInfo = DataSupport.findLast(MyInfo.class);
                myNet();
            }
        }
    }

    private void GetandSaveCurrentImage(){
        //1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        Bitmap Bmp = Bitmap.createBitmap( w, h, Bitmap.Config.ARGB_8888 );

        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();

        String SavePath = getSDCardPath()+"/MDeducation/ScreenImage";

        //3.保存Bitmap
        try {
            File path = new File(SavePath);
            //文件
            String filepath = SavePath + "/Screen_1.png";
            File file = new File(filepath);
            if(!path.exists()){
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                //由文件得到uri
                Uri imageUri = Uri.fromFile(new File(filepath));
                Log.d("share", "uri:" + imageUri);  //输出：file:///storage/emulated/0/test.jpg
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                shareIntent.setType("image/*");
                startActivity(Intent.createChooser(shareIntent, "分享到"));
                Toast.makeText(getApplicationContext(), "截屏文件已保存至SDCard/AndyDemo/ScreenImage/下", Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SDCard的目录路径功能
     * @return
     */
    private String getSDCardPath(){
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if(sdcardExist){
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }

}
